/**
 * <p>项目名：ViewPagerFragmentRadioGroup</p>
 * <p>包名：	com.my.viewpagerfragmentradiogroup</p>
 * <p>文件名：IndexFragment.java</p>
 * <p>版本信息： 2.1.0</p>
 * <p>日期： 2015/5/14/13:02.</p>
 * Copyright (c) 2015帮你公司-版权所有
 */
package com.tiantianyuegou.fragment;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.activity.GoodsListActivity;
import com.tiantianyuegou.activity.SearchActivity;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.ClassifyListModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.ToastUtils;
import com.tiantianyuegou.view.NoScrollGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 分类
 */
public class FenLeiFragment extends Fragment {


    private ListView list_fenlei;
    private NoScrollGridView gv_fenlei;
    TextView tv_search;
    MyAdapter mListAdapter;
    MyGridAdapter mGridAdapter;
    List<ClassifyListModel> ClassifyStyleInfoList;
    List<ClassifyListModel> ClassifyList;
    View rootView;
    BaseActivity activity;
   LoadingDialog loadingDialog;


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        activity = (BaseActivity) getActivity();
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_fenlei, container,
                    false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        findViewByIds();
        initdata();
        initListener();
        return rootView;
    }

    private void initdata() {
        loadingDialog = new LoadingDialog(activity);
        ClassifyStyleInfoList = new ArrayList<ClassifyListModel>();
        ClassifyList = new ArrayList<>();
        getData("0", "0");

    }

    private void findViewByIds() {
        list_fenlei = (ListView) rootView.findViewById(R.id.list_fenlei);
        gv_fenlei = (NoScrollGridView) rootView.findViewById(R.id.gv_fenlei);
        tv_search = (TextView) rootView.findViewById(R.id.tv_search);
    }

    int index = 0;

    private void initListener() {

        mListAdapter = new MyAdapter();
        mGridAdapter = new MyGridAdapter();
        list_fenlei.setAdapter(mListAdapter);
        gv_fenlei.setAdapter(mGridAdapter);

        list_fenlei.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                for (int i = 0; i < ClassifyStyleInfoList.size(); i++) {
                    ClassifyStyleInfoList.get(i).setIsSelect(false);
                }
                ClassifyStyleInfoList.get(position).setIsSelect(true);

                mListAdapter.notifyDataSetChanged();
                for (int i = 0; i < ClassifyList.size(); i++) {

                    ClassifyList.get(i).setIsSelect(false);
                }
                mGridAdapter.notifyDataSetChanged();


                /**
                 * 点击某个类型调某个类型的接口
                 */
                ClassifyList.removeAll(ClassifyList);
                //loadingDialog = new LoadingDialog(activity);

                getData(ClassifyStyleInfoList.get(position).getTpc_id() + "", "1");//调用数据接口
            }
        });
        gv_fenlei.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                for (int i = 0; i < ClassifyList.size(); i++) {
                    ClassifyList.get(i).setIsSelect(false);
                }

                //把选择的对象传到商品列表
                if (position > 0) {
//                  getData(ClassifyList.get(position).getTpc_id() + "", "2");//调用数据接口
                    ClassifyList.get(position).setIsSelect(true);
                    mGridAdapter.notifyDataSetChanged();
                    ClassifyListModel model = ClassifyList.get(position);
                    Intent intent = new Intent();
                    intent.putExtra("pcid", model.getTpc_id() + "");//传 饰品、家具某一个类型
                    intent.setClass(getActivity(), GoodsListActivity.class);
                    startActivity(intent);
                    System.out.println("---------" + model.getAllClassify() + "----------");
                    System.out.println("---------" + model.getTpc_id() + "----------");
                } else {  //点击全部的时候
                    ClassifyList.get(position).setIsSelect(true);
                    mGridAdapter.notifyDataSetChanged();
                    Intent intent = new Intent();
                    intent.putExtra("pcAllId", ClassifyStyleInfoList.get(index).getTpc_id() + "");
                    intent.setClass(getActivity(), GoodsListActivity.class);
                    startActivity(intent);
                }
            }
        });

        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent search = new Intent(getActivity(), SearchActivity.class);
                search.putExtra("type", "IndexFragment");
                startActivity(search);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //initdata();
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return ClassifyStyleInfoList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            if (ClassifyStyleInfoList != null) {
                return ClassifyStyleInfoList.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            convertView = LayoutInflater.from(getActivity()).inflate(R.layout.listitem_fenlei, null);

            TextView tv_item_roomstyle = (TextView) convertView
                    .findViewById(R.id.tv_itemfenlei);
            LinearLayout linear = (LinearLayout) convertView.findViewById(R.id.selector_item_linear);
            String type = ClassifyStyleInfoList.get(position)
                    .getAllClassify();
            if (type.length() > 4) {
                tv_item_roomstyle.setText(type.substring(0, 4) + "...");
            } else {
                tv_item_roomstyle.setText(type);
            }

            if (ClassifyStyleInfoList.get(position).isSelect()) {

                tv_item_roomstyle.setTextColor(getResources().getColor(
                        R.color.textcolor_red));
                linear.setBackground(getActivity().getResources().getDrawable(R.drawable.backgroud_fenlei_selector));

            } else {
                tv_item_roomstyle.setTextColor(getResources().getColor(
                        R.color.textcolor_black));
                linear.setBackground(getActivity().getResources().getDrawable(R.drawable.backgroud_fenlei_unselector));
            }

            return convertView;
        }

    }


    class MyGridAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return ClassifyList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder holder = null;

            if (convertView == null) {
                convertView = LayoutInflater.from(getActivity())
                        .inflate(R.layout.griditem_fenlei, null);

                holder = new ViewHolder();
                holder.tv_num1 = (TextView) convertView
                        .findViewById(R.id.tv_gridvfenlei);
                holder.linear = (LinearLayout) convertView.findViewById(R.id.selector_item_linear);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            String type=ClassifyList.get(position)
                    .getAllClassify();
            if(type.length()>4){
                holder.tv_num1.setText(type.substring(0,4)+"...");
            }else{
                holder.tv_num1.setText(type);
            }



            if (ClassifyList.get(position).isSelect()) {
                holder.tv_num1.setTextColor(getResources().getColor(R.color.textcolor_red));
                holder.linear.setBackground(getActivity().getResources().getDrawable(R.drawable.background_selector));

            } else {
                holder.tv_num1.setTextColor(getResources().getColor(R.color.textcolor_black));
                holder.linear.setBackground(getActivity().getResources().getDrawable(R.drawable.background_unselector));
            }

            return convertView;
        }

        class ViewHolder {
            TextView tv_num1;
            LinearLayout linear;

        }

    }

    private void getData(final String id, final String type) {
        if (!NetworkUtils.isNetworkAvailable(activity)) {
            activity.showMsg("请检查网络");
            return;
        }

        loadingDialog.setMsg("正在加载...");
        loadingDialog.show();

        RequestParams params = new RequestParams();
        params.addBodyParameter("parentId", id);
        activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.CATEGORY, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                loadingDialog.dismiss();
                String returnstr = responseInfo.result;
                Log.e("TAG", "response:" + returnstr);
                try {
                    JSONObject strObj = new JSONObject(returnstr);
                    String info = strObj.getString("info");
                    String code = strObj.getString("code");
                    if (code.equalsIgnoreCase("100")) {
                        if (info.contains("[")) {
                            ClassifyListModel modelAll = new ClassifyListModel();
                            modelAll.setAllClassify("全部");
                            if ("1".equals(type)) {
                                ClassifyList.add(modelAll);
                            }
                            JSONArray infoList = new JSONArray(info);
                            for (int i = 0; i < infoList.length(); i++) {
                                JSONObject temp = infoList.getJSONObject(i);
                                int tpc_id = temp.getInt("tpc_id");
                                String tpc_name = temp.getString("tpc_name");
                                ClassifyListModel classifyListBean = new ClassifyListModel();
                                classifyListBean.setAllClassify(tpc_name);
                                classifyListBean.setTpc_id(tpc_id);
                                if ("0".equals(type)) {
                                    ClassifyStyleInfoList.add(classifyListBean);
                                } else if ("1".equals(type)) {
                                    ClassifyList.add(classifyListBean);
                                }
                            }
                            System.out.println(ClassifyStyleInfoList.size() + "----------");
                            mListAdapter.notifyDataSetChanged();
                            if ("0".equals(type)) {
                                getData(ClassifyStyleInfoList.get(0).getTpc_id() + "", "1");
                                ClassifyStyleInfoList.get(0).setIsSelect(true);
                            }
                            mGridAdapter.notifyDataSetChanged();
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtils.showToast(getActivity(), "解析出错");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                ToastUtils.showToast(getActivity(), "failure");
            }
        });
    }

}



